package com.yeskery.nut.http;

import com.yeskery.nut.bind.ResponseBodyHandler;
import com.yeskery.nut.core.Request;
import com.yeskery.nut.core.Response;

import java.lang.reflect.Method;

/**
 * sse响应发射器处理器
 * @author YESKERY
 * 2024/7/12
 */
public class SseEmitterResponseBodyHandler implements ResponseBodyHandler {
    @Override
    public boolean support(Method method, Object result) {
        return SseEmitter.class.equals(result.getClass());
    }

    @Override
    public void handle(Object result, Request request, Response response) {
        SseEmitter sseEmitter = (SseEmitter) result;
        SseResponseEmitterHandler handler = new SseResponseEmitterHandler(sseEmitter, (BaseResponse) response);
        sseEmitter.setHandler(handler);
        afterInitialization(sseEmitter);
        handler.park();
    }

    @Override
    public boolean outputResponse() {
        return true;
    }

    @Override
    public int getOrder() {
        return ResponseBodyHandler.super.getOrder() - 1;
    }

    /**
     * 初始化完成回调
     * @param sseEmitter sse响应发射器
     */
    public void afterInitialization(SseEmitter sseEmitter) {
    }
}
